﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using com.codebump;
using System.Security.Cryptography;
using AuthorizeNet;
using System.Xml;
using System.IO;
using System.Data;
using System.Net;




public partial class Radiancy_Radiancy : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
        if (!IsPostBack)
        {
            if (Request.QueryString.HasKeys())
            {
                if (Request.QueryString["listid"] != String.Empty)
                    Session["listid"] = Request.QueryString["listid"];
                else
                    Session["listid"] = 1;


                if (Request.QueryString["dnis"] != null)
                {
                    Session["dnis"] = Request.QueryString["dnis"];
                }
                else
                {
                    Session["dnis"] = "9999999999";
                }
                if (Request.QueryString["ani"] != null)
                {
                    Session["ani"] = Request.QueryString["ani"];
                }
                else
                {
                    Session["ani"] = "9999999999";
                }

                Session["servername"] = Request.QueryString["servername"];
                Session["projectname"] = Request.QueryString["projectname"];
                Session["campaignname"] = Request.QueryString["campaignname"];
                Session["agentid"] = Request.QueryString["agentid"];
                Session["agentfirst"] = Request.QueryString["agentfirst"];
                Session["agentlast"] = Request.QueryString["agentlast"];
                
                Session["App"] = new DataAccess();
                ((DataAccess)Session["App"]).PutCallData("calldate", string.Format("{0:yyyy/MM/dd}", System.DateTime.Today));
                ((DataAccess)Session["App"]).CommitCallData();
            }
            
            //((DataAccess)Session["App"]).PutCallData("webtransfer", "8882785115");

            lblAgentName.Text = (Session["agentfirst"].ToString() + " " + Session["agentlast"].ToString()).Trim();
            Session["cInfo"] = false;

            if (Session["dnis"].ToString() == "2142959619")
            {
                lblEmployee.Visible = true;
                lblEmpOrder.Visible = true;
                cbEmployee.Checked = true;
                cbCharger.Visible = true;
                ddlOnePay.SelectedItem.Text = "Yes";
                ddlOnePay.Enabled = false;
                ddlPriorityShip.SelectedItem.Text = "No";
                ddlPriorityShip.Enabled = false;
                btnAutoDiscRebuttal.Visible = false;
                lbl1.Text = "$50.00 today";
                lbl2.Text = "$20.00";
                lbl3.Text = "$50.00";
                ddl2yrWarranty.SelectedItem.Text = "No";
                ddl2yrWarranty.Enabled = false;
                cbEmployee_CheckedChanged(null, null);
            }
            prepopulateFields();
        }
//       lblDNIS.Text = Session["dnis"].ToString();
    }

    public string prods = "";
    public double total = 0;
    public string sCust = "";
    public double additionalPay = 0;
    public double shipping = 0;
    public bool bInfoSubmitted = false;
    

    //POST LOGIC - For Step or Start pages
    //Add if statements as you add pages
    //For Next and Finish pages it is best to use the index in the if statements as below
    protected void WebWizard_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {

        int page = WebWizard.ActiveStepIndex;
        if (page == WebWizard.WizardSteps.IndexOf(this.Intro))
        {
            return;
        }

        if (page == WebWizard.WizardSteps.IndexOf(this.ConfirmOrder))
        {
            

        }

        if (page == WebWizard.WizardSteps.IndexOf(this.ConfirmOrder))
        {
            //if (lblCustDataEntered.Visible)
            //{
            //    //var nextbutton = WebWizard.FindControl("StepNavigationTemplateContainerID").FindControl("StepNextButton") as LinkButton;
            //    ((LinkButton)WebWizard.FindControl("StepNavigationTemplateContainerID").FindControl("StepNextButton")).Visible = false;
            //    return;
            //}
            //else
            //{
            //    //var nextbutton = WebWizard.FindControl("StepNavigationTemplateContainerID").FindControl("StepNextButton") as LinkButton;
            //    ((LinkButton)WebWizard.FindControl("StepNavigationTemplateContainerID").FindControl("StepNextButton")).Visible = true;
            //}



            //if (ddlProducts.SelectedItem.Text == "Choose One" && ddlProducts.Visible)
            //{
            //    lblNoProduct.Visible = true;
            //    return;
            //}
            //else
            //{
            //    lblNoProduct.Visible = false;
            //    //((DataAccess)Session["App"]).PutCallData("webusercode", "RS");
            //    //WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Disposition);
            //    return;
            //}
            
            
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Preauth))
        {
           
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Disposition))
        {
            return;
        }



    }

    //POST LOGIC for disposition pages
    //this is for pages that contain a disposition button
    protected void WebWizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {

        int page = WebWizard.ActiveStepIndex;
        if (page == WebWizard.WizardSteps.IndexOf(this.Intro))
        {
            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.ConfirmOrder))
        {
            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Preauth))
        {
            //Change These two lines of code - For Information Only

            //((DataAccess)Session["App"]).PutCallData("webusercode", "RS");
            //WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Disposition);
            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Disposition))
        {
            return;
        }


    }

    //PRE-LOGIC
    //Add if statements as needed for post-logic
    //You can use the Step ID name instead of the index as used in Next and Finish logic.
    protected void WebWizard_ActiveStepChanged(object sender, EventArgs e)
    {

        if (WebWizard.ActiveStep.Title.ToString() == "OnePayUpsell")
        {
            if (Convert.ToBoolean(Session["cInfo"]) == false)
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.CollectInfo);
                return;
            }
            if (cbEmployee.Checked)
            {
                pnlOnePay.Visible = true;
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.AdditionalUnit);
                return;
            }
        }
        
        if (WebWizard.ActiveStep.Title.ToString() == "NoNoPitch")
        {
            if (ddlUse.SelectedItem.Text == "Choose One")
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Intro);
                return;
            }
        }
        if (WebWizard.ActiveStep.Title.ToString() == "CollectInfo")
        {
            if (ddlColor.SelectedItem.Text == "Choose One")
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.NoNoPitch);
                return;
            }
        }

        if (WebWizard.ActiveStep.Title.ToString() == "OtherXsells")
        {
            if (ddlAddUnit.SelectedItem.Text == "Choose One")
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.AdditionalUnit);
                return;
            }
            
            if (ddlOnePay.SelectedItem.Text == "Yes")
            {
                pnl1Pay1.Visible = true;
                pnl1Pay2.Visible = true;
                pnl1pay3.Visible = true;
            }
            else
            {
                pnl1Pay1.Visible = false;
                pnl1Pay2.Visible = false;
                pnl1pay3.Visible = false;
            }
            if (ddlOnePay.SelectedItem.Text == "No")
            {
                pnl3pay1.Visible = true;
                pnl3pay2.Visible = true;
                pnl3pay3.Visible = true;
            }
            else
            {
                pnl3pay1.Visible = false;
                pnl3pay2.Visible = false;
                pnl3pay3.Visible = false;
            }
        }

        if (WebWizard.ActiveStep.Title.ToString() == "XSell2")
            if ((pnlFace.Visible && ddlFaceBundle.SelectedItem.Text == "Choose One") || 
                (pnlBodyBundle.Visible && ddlBodyBundle.SelectedItem.Text == "Choose One") || 
                (ddlSmooth.SelectedItem.Text == "Choose One"))
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.OtherXsells);
                return;
            }

        if (WebWizard.ActiveStep.Title.ToString() == "AdditionalUnit")
        {
            if (ddlOnePay.SelectedItem.Text == "Choose One" || (ddlOnePay.SelectedItem.Text == "No" && ddl2yrWarranty.SelectedItem.Text == "Choose One"))
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.OnePayUpsell);
                return;
            }
        }

        if (WebWizard.ActiveStep.Title.ToString() == "Disposition")
        {
             
            
            //These two lines should be fairly standard - they write the in-memory tables to the Database
            if (btnPreAuth.Enabled)
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Preauth);
                return;
            }
            else
            {
                DispoConfirm1.Visible = false;
                //foreach (DataRow r in ((DataAccess)Session["App"]).GetOrder().Rows)
                //{
                //    r["calldate"] = string.Format("{0:yyyy/MM/dd}", System.DateTime.Today);
                //}
                buildOrder2();
                //buildOrder();
                ((DataAccess)Session["App"]).CommitOrder();
                try
                {
                    lblXMLresult.Text = SubmitUDOAOrder();
                    //((DataAccess)Session["App"]).PutCallData("reference_number", lblXMLresult.Text);
                    ((DataAccess)Session["App"]).PutCallData("orderdate", string.Format("{0:yyyy/MM/dd}", System.DateTime.Today));
                    ((DataAccess)Session["App"]).PutCallData("webusercode", "RS");
                    ((DataAccess)Session["App"]).CommitCallData();
                    Response.Redirect("../DispositionComplete.aspx");
                }
                catch (Exception ex)
                {
                    lblXMLresult.Text = ex.ToString();
                    lblError.Text = ex.ToString();
                    //((DataAccess)Session["App"]).PutCallData("reference_number", lblXMLresult.Text);
                    ((DataAccess)Session["App"]).CommitCallData();
                    WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Preauth);
                }
                //foreach (System.Data.DataRow r in ((DataAccess)Session["App"]).GetProducts().Rows)
                //{
                //    ((DataAccess)Session["App"]).RemoveOrderItem(Convert.ToInt32(r["productid"]));
                //}

            }
            
            

            //((DataAccess)Session["App"]).PutOrderItem(Convert.ToInt32(ddlProducts.SelectedValue) ,1);
            
            
        }

        if (WebWizard.ActiveStep.Title.ToString() == "Preauth")
        {
            lblPreAuthResult.Text = "";
            if (ddlOrderClose.SelectedItem.Text != "Order Close - Sale")
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.ConfirmOrder);
                return;
            }
            //DispoDDL1.Visible = true;

            //((DataAccess)Session["App"]).PutCallData("webusercode", "");
            //((DataAccess)Session["App"]).CommitCallData();

            //foreach (System.Data.DataRow r in ((DataAccess)Session["App"]).GetProducts().Rows)
            //{
            //    ((DataAccess)Session["App"]).RemoveOrderItem(Convert.ToInt32(r["productid"]));
            //}
            //((DataAccess)Session["App"]).CommitOrder();
                                               
        }

        if (WebWizard.ActiveStep.Title.ToString() == "ConfirmOrder")                                                        //*********   ITEMS ADDED HERE     ****************************
        {
            if (ddlSkin.SelectedItem.Text == "Choose One" || ddlPriorityShip.SelectedItem.Text == "Choose One")
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.XSell2);
                return;
            }

            //buildOrder();
            buildOrder2();
            
              
            
        } 

    } //end PRE-LOGIC                             //end PRE-LOGIC                        //end PRE-LOGIC                     //end PRE-LOGIC                    //end PRE-LOGIC

    protected void buildOrder()
    {
        ((DataAccess)Session["App"]).GetOrder().Rows.Clear();
        total = 0;
        prods = "";
        additionalPay = 0;
        shipping = 0;
        prods = ddlColor.SelectedItem.Text + " NoNo!";

        if (!cbEmployee.Checked)
        {
            addMainProd();
            if (ddlAddUnit.SelectedItem.Text != "No")
            {
                addAddProd();
            }
            if (ddlOnePay.SelectedItem.Text == "Yes")
            {
                ((DataAccess)Session["App"]).PutOrderItem(341, 1);
                shipping = 0;
            }
            if (ddlOnePay.SelectedValue == "0" && ddl2yrWarranty.SelectedValue == "19.95")
            {
                total = total + 19.95;
                prods = prods + ", plus the upgrade 2-year warranty";
                //((DataAccess)Session["App"]).PutOrderItem("productcode", "1");
                ((DataAccess)Session["App"]).PutOrderItem(342, 1);
            }
            if (ddlAddUnit.SelectedItem.Text == "Pink" || ddlAddUnit.SelectedItem.Text == "Silver" || ddlAddUnit.SelectedItem.Text == "Black")
            {
                total = total + (199 * Int32.Parse(ddlAddUnitQty.SelectedValue));
                prods = prods + ", plus an additional " + ddlAddUnitQty.SelectedValue + " " + ddlAddUnit.SelectedItem.Text + " NoNo! Hair unit(s)";

            }
            if (ddlFaceBundle.SelectedItem.Text == "Yes" && ddlOnePay.SelectedValue == "269.85")
            {
                total = total + (79.95 * Int32.Parse(ddlFaceBundleQty.SelectedValue));
                prods = prods + ", plus " + ddlFaceBundleQty.SelectedValue + " NoNo! Face bundle(s)";
                ((DataAccess)Session["App"]).PutOrderItem(334, Int32.Parse(ddlFaceBundleQty.SelectedValue));
            }
            if (ddlFaceBundle.SelectedItem.Text == "Yes" && ddlOnePay.SelectedValue == "0" && !cbDownsell.Checked)
            {
                total = total + (26.65 * Int32.Parse(ddlFaceBundleQty.SelectedValue));
                prods = prods + ", plus " + ddlFaceBundleQty.SelectedValue + " NoNo! Face bundle(s)";
                additionalPay = additionalPay + (26.65 * Int32.Parse(ddlFaceBundleQty.SelectedValue));
                ((DataAccess)Session["App"]).PutOrderItem(334, Int32.Parse(ddlFaceBundleQty.SelectedValue));
            }
            if (ddlBodyBundle.SelectedItem.Text == "Yes" && ddlOnePay.SelectedValue == "269.85")
            {
                total = total + (59.85 * Int32.Parse(ddlBodyBundleQty.SelectedValue));
                prods = prods + ", plus " + ddlBodyBundleQty.SelectedValue + " NoNo! Body bundle(s)";
                ((DataAccess)Session["App"]).PutOrderItem(335, Int32.Parse(ddlBodyBundleQty.SelectedValue));
            }
            if (ddlBodyBundle.SelectedItem.Text == "Yes" && ddlOnePay.SelectedValue == "0" && !cbDownsell.Checked)
            {
                total = total + (19.95 * Int32.Parse(ddlBodyBundleQty.SelectedValue));
                prods = prods + ", plus " + ddlBodyBundleQty.SelectedValue + " NoNo! Body bundle(s)";
                additionalPay = additionalPay + (19.95 * Int32.Parse(ddlBodyBundleQty.SelectedValue));
                ((DataAccess)Session["App"]).PutOrderItem(335, Int32.Parse(ddlBodyBundleQty.SelectedValue));
            }
            if (ddlSmooth.SelectedItem.Text == "Yes" && ddlOnePay.SelectedValue == "269.85")
            {
                total = total + (39.75 * Int32.Parse(ddlSmoothQty.SelectedValue));
                prods = prods + ", plus " + ddlSmoothQty.SelectedValue + " NoNo! Smooth All Over bundle(s)";
                ((DataAccess)Session["App"]).PutOrderItem(426, Int32.Parse(ddlSmoothQty.SelectedValue));
            }
            if (ddlSmooth.SelectedItem.Text == "Yes" && ddlOnePay.SelectedValue == "0" && !cbDownsell.Checked)
            {
                total = total + (13.25 * Int32.Parse(ddlSmoothQty.SelectedValue));
                prods = prods + ", plus " + ddlSmoothQty.SelectedValue + " NoNo! Smooth All Over bundle(s)";
                additionalPay = additionalPay + (13.25 * Int32.Parse(ddlSmoothQty.SelectedValue));
                ((DataAccess)Session["App"]).PutOrderItem(426, Int32.Parse(ddlSmoothQty.SelectedValue));
            }
            if (ddlSkin.SelectedItem.Text == "Yes")
            {
                total = total + (110 * Int32.Parse(ddlSkinQty.SelectedValue));
                prods = prods + ", plus " + ddlSkinQty.SelectedValue + " NoNo! Skin Acne Treatment System";
                ((DataAccess)Session["App"]).PutOrderItem(427, Int32.Parse(ddlSkinQty.SelectedValue));
            }
            if (ddlPriorityShip.SelectedItem.Text == "Yes" && ddlOnePay.SelectedItem.Text == "Yes")
            {
                shipping = 12.95;
                prods = prods + ", plus priority shipping";
                ((DataAccess)Session["App"]).PutOrderItem(332, 1);
            }
            //if (ddlPriorityShip.SelectedItem.Text == "Yes" && ddlOnePay.SelectedItem.Text == "No")
            //{
            //    shipping = 27.90; //+= b/c for non one-pay shipping isn't free
            //    //total = total + shipping;
            //    prods = prods + ", plus priority shipping";
            //    ((DataAccess)Session["App"]).PutOrderItem(333, 1);
            //}
            if (ddlOnePay.SelectedItem.Text == "No")
            {
                if (ddlPriorityShip.SelectedItem.Text == "Yes")
                {
                    shipping = 27.90;
                    ((DataAccess)Session["App"]).PutOrderItem(333, 1);
                }
                else
                {
                    shipping = 14.95;
                    ((DataAccess)Session["App"]).PutOrderItem(331, 1);
                }
                //pnlTrialConf.Visible = true;
                //total = total + shipping;
                if (ddlFaceBundle.SelectedItem.Text == "Yes")
                {
                    additionalPay = additionalPay + (26.65 * Int32.Parse(ddlFaceBundleQty.SelectedValue));
                    prods = prods + ", plus " + ddlFaceBundleQty.SelectedValue + " NoNo! Face bundle(s)";
                    ((DataAccess)Session["App"]).PutOrderItem(334, Int32.Parse(ddlFaceBundleQty.SelectedValue));
                }
                if (ddlBodyBundle.SelectedItem.Text == "Yes")
                {
                    additionalPay = additionalPay + (19.95 * Int32.Parse(ddlBodyBundleQty.SelectedValue));
                    prods = prods + ", plus " + ddlBodyBundleQty.SelectedValue + " NoNo! Body bundle(s)";
                    ((DataAccess)Session["App"]).PutOrderItem(335, Int32.Parse(ddlBodyBundleQty.SelectedValue));
                }
                if (ddlSmooth.SelectedItem.Text == "Yes")
                {
                    additionalPay = additionalPay + (13.25 * Int32.Parse(ddlSmoothQty.SelectedValue));
                    prods = prods + ", plus " + ddlSmoothQty.SelectedValue + " NoNo! Smooth All Over bundle(s)";
                    ((DataAccess)Session["App"]).PutOrderItem(426, Int32.Parse(ddlSmoothQty.SelectedValue));
                }
                //additionalPay += 89.95;
                ////lblTrialProds.Text = prods;
                //////total = total + additionalPay;
                ////lblAddPay.Text = additionalPay.ToString();
                ////lblTrialTotal.Text = total.ToString();
                //the next two lines add standard shipping to the totals AFTER the text has been written
                ////this is done b/c + 14.95 is written in the text by trialtotal.
                //shipping += 14.95;
                //total += 14.95;
                ((DataAccess)Session["App"]).PutCallData("webtransfer", "TRILFR");
            }
            else
            {
                pnlTrialConf.Visible = false;
            }
            if (ddlOnePay.SelectedValue == "269.85")
            {
                pnl1PayConf.Visible = true;
                total += 269.85;
                //shipping = 0;
                //total = total + shipping;
                ////lbl1PayProds.Text = prods;
                ////lbl1PayTotal.Text = total.ToString();
                ((DataAccess)Session["App"]).PutCallData("webtransfer", "ONEPFR");
            }
            else
            {
                pnl1PayConf.Visible = false;
            }
            if (!cbDownsell.Checked && ddlOnePay.SelectedValue == "0") //not a downsell, but is a 3 pay
            {
                pnl3PayConf.Visible = true;
                additionalPay += 89.95;
                total += 89.95;
                //total = total + shipping;
                ////lbl3PayProds.Text = prods;
                ////lbl3PayTotal.Text = total.ToString();
                ////lblAdditionalPay.Text = additionalPay.ToString();
                ((DataAccess)Session["App"]).PutCallData("webtransfer", "BAS1FR");
            }
            else
            {
                pnl3PayConf.Visible = false;
            }
            if (cbDownsell.Checked)
            {
                pnlTrialConf.Visible = true;
            }
            //if (ddlOnePay.SelectedItem.Text == "No")
            //{
            //    ((DataAccess)Session["App"]).PutOrderItem(331, 1);
            //}
            //total = total + shipping;
            total += shipping;


            lblTrialProds.Text = prods;
            //total = total + additionalPay;
            lblAddPay.Text = additionalPay.ToString();
            lblTrialTotal.Text = total.ToString();


            lbl1PayProds.Text = prods;
            lbl1PayTotal.Text = total.ToString();


            lbl3PayProds.Text = prods;
            lbl3PayTotal.Text = total.ToString();
            lblAdditionalPay.Text = additionalPay.ToString();

            lblShip.Text = shipping.ToString();
            lblAmount.Text = total.ToString();

        }
        if (cbEmployee.Checked)
        {
            shipping = 0;
            addMainProd();
            if (ddlAddUnit.SelectedItem.Text != "No")
            {
                addAddProd();
            }
            //if (ddl2yrWarranty.SelectedValue == "19.95")
            //{
            //    total = total + 19.95;
            //    prods = prods + ", plus the upgrade 2-year warranty";  //the employee purchase receives free lifetime warranty
            //    ((DataAccess)Session["App"]).PutOrderItem(342, 1);
            //}
            if (ddlAddUnit.SelectedItem.Text == "Pink" || ddlAddUnit.SelectedItem.Text == "Silver" || ddlAddUnit.SelectedItem.Text == "Black")
            {
                total += (199 * Int32.Parse(ddlAddUnitQty.SelectedValue));
                prods += ", plus an additional " + ddlAddUnitQty.SelectedValue + " " + ddlAddUnit.SelectedItem.Text + " NoNo! Hair unit(s)";
            }
            if (ddlFaceBundle.SelectedItem.Text == "Yes")
            {
                total = total + (79.95 * Int32.Parse(ddlFaceBundleQty.SelectedValue));
                prods = prods + ", plus " + ddlFaceBundleQty.SelectedValue + " NoNo! Face bundle(s)";
                ((DataAccess)Session["App"]).PutOrderItem(334, Int32.Parse(ddlFaceBundleQty.SelectedValue));
            }
            if (ddlBodyBundle.SelectedItem.Text == "Yes")
            {
                total = total + (59.85 * Int32.Parse(ddlBodyBundleQty.SelectedValue));
                prods = prods + ", plus " + ddlBodyBundleQty.SelectedValue + " NoNo! Body bundle(s)";
                ((DataAccess)Session["App"]).PutOrderItem(335, Int32.Parse(ddlBodyBundleQty.SelectedValue));
            }
            if (ddlSmooth.SelectedItem.Text == "Yes")  //COMPACKEMP
            {
                total = total + (20 * Int32.Parse(ddlSmoothQty.SelectedValue));
                prods = prods + ", plus " + ddlSmoothQty.SelectedValue + " NoNo! Smooth All Over bundle(s)";
                ((DataAccess)Session["App"]).PutOrderItem(378, Int32.Parse(ddlSmoothQty.SelectedValue));
            }
            if (ddlSkin.SelectedItem.Text == "Yes")
            {
                total = total + (50 * Int32.Parse(ddlSkinQty.SelectedValue));
                prods = prods + ", plus " + ddlSkinQty.SelectedValue + " NoNo! Skin Acne Treatment System";
                ((DataAccess)Session["App"]).PutOrderItem(377, Int32.Parse(ddlSkinQty.SelectedValue));
            }
            if (cbCharger.Checked)
            {
                total = total + 19.95;
                prods = prods + ", plus an additional charger";
                ((DataAccess)Session["App"]).PutOrderItem(379, 1);
            }

            //if (ddlOnePay.SelectedValue == "0")
            //{
            //    pnl1PayConf.Visible = true;
            //    total = total + 50;
            //    lbl1PayProds.Text = prods;
            //    lbl1PayTotal.Text = total.ToString();
            //}
            //if (!cbDownsell.Checked)
            //{
            pnl1PayConf.Visible = true;
            //additionalPay = additionalPay + 89.95;
            total = total + 50;
            lbl1PayProds.Text = prods;
            lbl1PayTotal.Text = total.ToString();
            //lblAdditionalPay.Text = additionalPay.ToString();
            //}
            lblAmount.Text = total.ToString();


        }
    }
    protected void addMainProd()
    {
        if (!cbEmployee.Checked)
        {
            switch (ddlColor.SelectedIndex)
            {
                case 1:
                    ((DataAccess)Session["App"]).PutOrderItem(424, 1);
                    return;
                case 2:
                    ((DataAccess)Session["App"]).PutOrderItem(425, 1);
                    return;
                case 3:
                    ((DataAccess)Session["App"]).PutOrderItem(423, 1);
                    return;
                default:
                    ((DataAccess)Session["App"]).PutOrderItem(424, 1);
                    return;
            }
        }
        else
        {
            switch (ddlColor.SelectedIndex)
            {
                case 1:
                    ((DataAccess)Session["App"]).PutOrderItem(374, 1);
                    return;
                case 2:
                    ((DataAccess)Session["App"]).PutOrderItem(375, 1);
                    return;
                default:
                    ((DataAccess)Session["App"]).PutOrderItem(375, 1);
                    return;
            }
        }
    }

    protected void addAddProd()
    {
        switch (ddlAddUnit.SelectedIndex)
        {
            case 1:
                ((DataAccess)Session["App"]).PutOrderItem(429, Int32.Parse(ddlAddUnitQty.SelectedValue));
                return;
            case 2:
                ((DataAccess)Session["App"]).PutOrderItem(430, Int32.Parse(ddlAddUnitQty.SelectedValue));
                return;
            case 3:
                ((DataAccess)Session["App"]).PutOrderItem(428, Int32.Parse(ddlAddUnitQty.SelectedValue));
                return;
            default:
                ((DataAccess)Session["App"]).PutOrderItem(430, Int32.Parse(ddlAddUnitQty.SelectedValue));
                return;
        }
        //switch (ddlAddUnit.SelectedIndex)
        //{
        //    case 1:
        //        ((DataAccess)Session["App"]).PutOrderItem(339, 1);
        //        return;
        //    case 2:
        //        ((DataAccess)Session["App"]).PutOrderItem(340, 1);
        //        return;
        //    case 3:
        //        ((DataAccess)Session["App"]).PutOrderItem(338, 1);
        //        return;
        //    default:
        //        ((DataAccess)Session["App"]).PutOrderItem(340, 1);
        //        return;
        //}
    }

    protected void btnAutoDiscRebuttal_Click(object sender, EventArgs e)
    {
        Panel1.Visible = !Panel1.Visible;
    }

 
    protected void btnSubmit_Click(object sender, System.EventArgs e)
    {
        lblError.Text = "";

        bool bCustValid = false;
        bool ccCheck = false;
        //bool ecCheck = false;
        bool bShipValid = false;

        //int result;

        bCustValid = !(string.IsNullOrEmpty(tbFirstName.Text) ||
            string.IsNullOrEmpty(tbLastName.Text) ||
            string.IsNullOrEmpty(tbAddr.Text) ||
            //string.IsNullOrEmpty(tbAddr2.Text) ||
            string.IsNullOrEmpty(tbZip.Text));
            //string.IsNullOrEmpty(ddlCity.SelectedItem.Text) ||
            //string.IsNullOrEmpty(ddlState.SelectedItem.Text) ||
            //string.IsNullOrEmpty(ddlCountry.SelectedItem.Text)) &&
            //(ddlCity.SelectedIndex > 0);

        //bCustValid = ! &(string.IsNullOrEmpty(tbFirstName.Text) ||
        //    string.IsNullOrEmpty(tbLastName.Text) ||
        //    string.IsNullOrEmpty(tbAddr.Text) ||
        //    //string.IsNullOrEmpty(tbAddr2.Text) ||
        //    string.IsNullOrEmpty(tbZip.Text) ||
        //    string.IsNullOrEmpty(ddlCity.SelectedItem.Text) ||
        //    ddlState.Items.Count <= 0 ||
        //    string.IsNullOrEmpty(ddlState.SelectedItem.Text) ||
        //    string.IsNullOrEmpty(ddlCountry.SelectedItem.Text)) &&
        //    (ddlCity.SelectedIndex > 0);

        ccCheck = !(string.IsNullOrEmpty(ddlCardType.SelectedItem.Text) ||
            string.IsNullOrEmpty(tbCCNumber.Text) ||
            string.IsNullOrEmpty(tbCCV.Text) ||
            string.IsNullOrEmpty(tbExpDate.Text) || //&&
            (tbExpDate.Text.Length < 4) ||          //this has to be before the convert.toint32 statement on it so it fails before attempting that. Otherwise it throws a yellow screen.
            Convert.ToInt32(tbExpDate.Text.Substring(0, 2)) > 12) &&
            (((DataAccess)Session["App"]).IsValidCC(GetCardType(ddlCardType.SelectedValue), tbCCNumber.Text)) &&
            (System.Text.RegularExpressions.Regex.IsMatch(tbCCV.Text, @"^[\d]+$")) &&
            (System.Text.RegularExpressions.Regex.IsMatch(tbExpDate.Text, @"^[\d]+$"));
            //(Int32.TryParse(tbCCV.Text, out result)) &&
            //(Int32.TryParse(tbExpDate.Text, out result)) &&
            



        //ecCheck = !(string.IsNullOrEmpty(tbBankName.Text) ||
        //    string.IsNullOrEmpty(tbAccNum.Text) ||
        //    string.IsNullOrEmpty(tbRoutNum.Text) ||
        //    string.IsNullOrEmpty(tbBankCity.Text) ||
        //    string.IsNullOrEmpty(tbCheckNum.Text)) &&
        //    (Int32.TryParse(tbAccNum.Text, out result)) &&
        //    (Int32.TryParse(tbRoutNum.Text, out result)) &&
        //    (Int32.TryParse(tbCheckNum.Text, out result));

        //bShipValid = !(string.IsNullOrEmpty(tbShipAddr.Text) ||
        //    //string.IsNullOrEmpty(tbShipaddr2.Text) ||
        //    string.IsNullOrEmpty(tbShipZip.Text) ||
        //    string.IsNullOrEmpty(ddlShipCity.SelectedItem.Text) ||
        //    string.IsNullOrEmpty(ddlShipState.SelectedItem.Text) ||
        //    string.IsNullOrEmpty(ddlShipCountry.SelectedItem.Text)) &&
        //    (ddlShipCity.SelectedIndex > 0) &&
        //    (tbShipZip.Text.Length >= 5) &&
        //    (tbShipZip.Text.Length <= 7);

        bShipValid = !(string.IsNullOrEmpty(tbShipAddr.Text) ||
            //string.IsNullOrEmpty(tbShipaddr2.Text) ||
            string.IsNullOrEmpty(tbShipZip.Text) ||
            string.IsNullOrEmpty(ddlShipCity.SelectedItem.Text) ||
            //ddlShipState.Items.Count > 0 ||
            string.IsNullOrEmpty(ddlShipState.SelectedItem.Text) ||
            string.IsNullOrEmpty(ddlShipCountry.SelectedItem.Text)) &&
            (ddlShipCity.SelectedIndex > 0) &&
            (tbShipZip.Text.Length >= 5) &&
            (tbShipZip.Text.Length <= 7);

        if (bCustValid)
        {
            ((DataAccess)Session["App"]).PutCallData("firstname", tbFirstName.Text);
            ((DataAccess)Session["App"]).PutCallData("lastname", tbLastName.Text);
            ((DataAccess)Session["App"]).PutCallData("address1", tbAddr.Text);
            if (!string.IsNullOrEmpty(tbAddr2.Text))
                ((DataAccess)Session["App"]).PutCallData("address2", tbAddr2.Text);
            else
                ((DataAccess)Session["App"]).PutCallData("address2", "");
            ((DataAccess)Session["App"]).PutCallData("Zip", tbZip.Text);
            ((DataAccess)Session["App"]).PutCallData("City", tbCity.Text);
            ((DataAccess)Session["App"]).PutCallData("State", tbState.Text);
            ((DataAccess)Session["App"]).PutCallData("Country", ddlCountry.SelectedItem.Text);

            if (!cbShipping.Checked)
            {
                //((DataAccess)Session["App"]).PutCallData("ShipAddress1", tbAddr.Text);
                //if (!string.IsNullOrEmpty(tbAddr2.Text))
                //    ((DataAccess)Session["App"]).PutCallData("ShipAddress2", tbAddr2.Text);
                //else
                //    ((DataAccess)Session["App"]).PutCallData("ShipAddress2", "");
                //((DataAccess)Session["App"]).PutCallData("ShipZip", tbZip.Text);
                //((DataAccess)Session["App"]).PutCallData("ShipCity", ddlCity.SelectedItem.Text);
                //((DataAccess)Session["App"]).PutCallData("ShipState", ddlState.SelectedItem.Text);
                //((DataAccess)Session["App"]).PutCallData("ShipCountry", ddlCountry.SelectedItem.Text);
            }
            else
            {
                if (bShipValid)
                {
                    ((DataAccess)Session["App"]).PutCallData("ShipAddress1", tbShipAddr.Text);
                    if (!string.IsNullOrEmpty(tbShipAddr.Text))
                        ((DataAccess)Session["App"]).PutCallData("ShipAddress2", tbShipaddr2.Text);
                    else
                        ((DataAccess)Session["App"]).PutCallData("ShipAddress2", "");
                    ((DataAccess)Session["App"]).PutCallData("ShipZip", tbShipZip.Text);
                    ((DataAccess)Session["App"]).PutCallData("ShipCity", ddlShipCity.SelectedItem.Text);
                    ((DataAccess)Session["App"]).PutCallData("ShipState", ddlShipState.SelectedItem.Text);
                    ((DataAccess)Session["App"]).PutCallData("ShipCountry", ddlShipCountry.SelectedItem.Text);
                }
                else
                {
                    lblError.Text += "Enter Shipping Info<br/>";
                }
            }
        }
        else
        {
            if (ddlCity.SelectedIndex == 0)
                lblError.Text += "Select a City<br/>";
            else
                lblError.Text += "Enter Valid Customer Data<br/>";
        }

        if ((!string.IsNullOrEmpty(tbPhone.Text)) && ((tbPhone.Text.Length != 10) || !(System.Text.RegularExpressions.Regex.Match(tbPhone.Text, @"^[1-9]\d{2}[1-9]\d{6}$").Success)))
        {
            lblError.Text += "Invalid Phone<br/>";
        }
        else
        {
            if (!string.IsNullOrEmpty(tbPhone.Text))
                ((DataAccess)Session["App"]).PutCallData("PrimaryPhone", tbPhone.Text);
        }

        if ((!string.IsNullOrEmpty(tbEmail.Text)) && !((DataAccess)Session["App"]).IsValidEmail(tbEmail.Text))
        {
            lblError.Text += "Invalid Email<br/>";
        }
        else
        {
            if (!string.IsNullOrEmpty(tbEmail.Text))
                ((DataAccess)Session["App"]).PutCallData("Email", tbEmail.Text);
        }


        if (ddlPaymentType.SelectedIndex == 1) // debit/credit
        {
            ((DataAccess)Session["App"]).PutCallData("PaymentType", ddlPaymentType.SelectedItem.Value);

            if (ccCheck)
            {
                //((DataAccess)Session["App"]).PutCallData("CCType", ddlCardType.SelectedItem.Value);
                //((DataAccess)Session["App"]).PutCallData("CCNumber", ((DataAccess)Session["App"]).EnryptData(tbCCNumber.Text));
                //((DataAccess)Session["App"]).PutCallData("CCV", ((DataAccess)Session["App"]).EnryptData(tbCCV.Text));
                //((DataAccess)Session["App"]).PutCallData("CCExpDate", tbExpDate.Text);
            }
            else
            {
                lblError.Text += "Invalid Card Info<br/>";
            }
        }
        //else if (ddlPaymentType.SelectedIndex == 2) // echeck
        //{
        //    ((DataAccess)Session["App"]).PutCallData("PaymentType", ddlPaymentType.SelectedItem.Value);

        //    if (ecCheck)
        //    {
        //        ((DataAccess)Session["App"]).PutCallData("ECBankName", tbBankName.Text);
        //        ((DataAccess)Session["App"]).PutCallData("BankCity", tbBankCity.Text);
        //        ((DataAccess)Session["App"]).PutCallData("ECAccNumber", tbAccNum.Text);
        //        ((DataAccess)Session["App"]).PutCallData("ECRoutingNumber", tbRoutNum.Text);
        //        ((DataAccess)Session["App"]).PutCallData("ECCheckNumber", tbCheckNum.Text);
        //        ((DataAccess)Session["App"]).PutCallData("ECAccType", ddlAccType.SelectedItem.Text);
        //    }
        //    else
        //    {
        //        lblError.Text += "Invalid Bank Info<br/>";
        //    }
        //}
        else
        {
            //lblError.Text += "Please select a payment method." + Environment.NewLine;
        }

        if (bCustValid == true && ccCheck == true)
        {
            if (cbShipping.Checked && bShipValid == false)
            {
            }
            else
            {
                Session["cInfo"] = true;
            }
        }
        else
        {
            Session["cInfo"] = false;
        }

    }


    protected void ddlPaymentType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlPaymentType.SelectedValue == "CC")
        {
            trCCNumber.Visible = true;
            trCCType.Visible = true;
            trCCExpDate.Visible = true;
            trCCV.Visible = true;
            trECAccNum.Visible = false;
            trECBankName.Visible = false;
            trECCheckNum.Visible = false;
            trECRoutNum.Visible = false;
            trBankCity.Visible = false;
            trECAccType.Visible = false;
        }
        else if (ddlPaymentType.SelectedValue == "EC")
        {
            trCCNumber.Visible = false;
            trCCType.Visible = false;
            trCCExpDate.Visible = false;
            trCCV.Visible = false;
            trECAccNum.Visible = true;
            trECBankName.Visible = true;
            trBankCity.Visible = true;
            trECCheckNum.Visible = true;
            trECRoutNum.Visible = true;
            trECAccType.Visible = true;
        }
        else
        {
            trCCNumber.Visible = false;
            trCCType.Visible = false;
            trCCExpDate.Visible = false;
            trCCV.Visible = false;
            trECAccNum.Visible = false;
            trECBankName.Visible = false;
            trECCheckNum.Visible = false;
            trECRoutNum.Visible = false;
            trECAccType.Visible = false;
            trBankCity.Visible = false;
        }

    }

    protected void cbShipping_CheckedChanged(object sender, EventArgs e)
    {
        if (cbShipping.Checked)
        {
            trShipAddr.Visible = true;
            trShipAddr2.Visible = true;
            trShipCity.Visible = true;
            trShipState.Visible = true;
            trShipCountry.Visible = true;
            trShipZip.Visible = true;
            trShipLbl.Visible = true;
            trShipSearchZip.Visible = true;

        }
        else
        {
            trShipAddr.Visible = false;
            trShipAddr2.Visible = false;
            trShipCity.Visible = false;
            trShipState.Visible = false;
            trShipCountry.Visible = false;
            trShipZip.Visible = false;
            trShipLbl.Visible = false;
            trShipSearchZip.Visible = false;
        }
    }

    protected void btnSearchZip_Click(object sender, EventArgs e)
    {
        ValidateZip(tbZip.Text.ToUpper(), ddlCity, ddlState, ddlCountry);
                ddlState.Enabled = true;
                if (ddlCountry.SelectedItem.Text == "USA")
                {
                    switch (ddlState.Text)
                    {
                        case "AK": lblState.Text = "Alaska"; ddlState.Enabled = false; return;
                        case "AL": lblState.Text = "Alabama"; ddlState.Enabled = false; return;
                        case "AR": lblState.Text = "Arkansas"; ddlState.Enabled = false; return;
                        case "AZ": lblState.Text = "Arizona"; ddlState.Enabled = false; return;
                        case "CA": lblState.Text = "California"; ddlState.Enabled = false; return;
                        case "CO": lblState.Text = "Colorado"; ddlState.Enabled = false; return;
                        case "CT": lblState.Text = "Connecticut"; ddlState.Enabled = false; return;
                        case "DC": lblState.Text = "District of Columbia"; ddlState.Enabled = false; return;
                        case "DE": lblState.Text = "Delaware"; ddlState.Enabled = false; return;
                        case "FL": lblState.Text = "Florida"; ddlState.Enabled = false; return;
                        case "GA": lblState.Text = "Georgia"; ddlState.Enabled = false; return;
                        case "HI": lblState.Text = "Hawaii"; ddlState.Enabled = false; return;
                        case "IA": lblState.Text = "Iowa"; ddlState.Enabled = false; return;
                        case "ID": lblState.Text = "Idaho"; ddlState.Enabled = false; return;
                        case "IL": lblState.Text = "Illinois"; ddlState.Enabled = false; return;
                        case "IN": lblState.Text = "Indiana"; ddlState.Enabled = false; return;
                        case "KS": lblState.Text = "Kansas"; ddlState.Enabled = false; return;
                        case "KY": lblState.Text = "Kentucky"; ddlState.Enabled = false; return;
                        case "LA": lblState.Text = "Louisiana"; ddlState.Enabled = false; return;
                        case "MA": lblState.Text = "Massachusetts"; ddlState.Enabled = false; return;
                        case "MD": lblState.Text = "Maryland"; ddlState.Enabled = false; return;
                        case "ME": lblState.Text = "Maine"; ddlState.Enabled = false; return;
                        case "MI": lblState.Text = "Michigan"; ddlState.Enabled = false; return;
                        case "MN": lblState.Text = "Minnesota"; ddlState.Enabled = false; return;
                        case "MO": lblState.Text = "Missouri"; ddlState.Enabled = false; return;
                        case "MS": lblState.Text = "Mississippi"; ddlState.Enabled = false; return;
                        case "MT": lblState.Text = "Montana"; ddlState.Enabled = false; return;
                        case "NC": lblState.Text = "North Carolina"; ddlState.Enabled = false; return;
                        case "ND": lblState.Text = "North Dakota"; ddlState.Enabled = false; return;
                        case "NE": lblState.Text = "Nebraska"; ddlState.Enabled = false; return;
                        case "NH": lblState.Text = "New Hampshire"; ddlState.Enabled = false; return;
                        case "NJ": lblState.Text = "New Jersey"; ddlState.Enabled = false; return;
                        case "NM": lblState.Text = "New Mexico"; ddlState.Enabled = false; return;
                        case "NV": lblState.Text = "Nevada"; ddlState.Enabled = false; return;
                        case "NY": lblState.Text = "New York"; ddlState.Enabled = false; return;
                        case "OH": lblState.Text = "Ohio"; ddlState.Enabled = false; return;
                        case "OK": lblState.Text = "Oklahoma"; ddlState.Enabled = false; return;
                        case "OR": lblState.Text = "Oregon"; ddlState.Enabled = false; return;
                        case "PA": lblState.Text = "Pennsylvania"; ddlState.Enabled = false; return;
                        case "RI": lblState.Text = "Rhode Island"; ddlState.Enabled = false; return;
                        case "SC": lblState.Text = "South Carolina"; ddlState.Enabled = false; return;
                        case "SD": lblState.Text = "South Dakota"; ddlState.Enabled = false; return;
                        case "TN": lblState.Text = "Tennessee"; ddlState.Enabled = false; return;
                        case "TX": lblState.Text = "Texas"; ddlState.Enabled = false; return;
                        case "UT": lblState.Text = "Utah"; ddlState.Enabled = false; return;
                        case "VA": lblState.Text = "Virginia"; ddlState.Enabled = false; return;
                        case "VT": lblState.Text = "Vermont"; ddlState.Enabled = false; return;
                        case "WA": lblState.Text = "Washington"; ddlState.Enabled = false; return;
                        case "WI": lblState.Text = "Wisconsin"; ddlState.Enabled = false; return;
                        case "WV": lblState.Text = "West Virginia"; ddlState.Enabled = false; return;
                        case "WY": lblState.Text = "Wyoming"; ddlState.Enabled = false; return;
                        case "PR": lblState.Text = "Puerto Rico"; ddlState.Enabled = false; return;
                        default:
                            lblState.Text = "[make sure a state is selected]"; 
                            ddlState.Enabled = false;
                            return;
                    }
                }
                else
                {
                    lblState.Text = "CANADA";
                }
           
           
    }

    protected void btnShipSearchZip_Click(object sender, EventArgs e)
    {
        ValidateZip(tbShipZip.Text.ToUpper(), ddlShipCity, ddlShipState, ddlShipCountry);
    }

    protected void ValidateZip(string strZip, DropDownList ddl_City, DropDownList ddl_State, DropDownList ddl_Country)
    {

        ddl_City.Items.Clear();
        ddl_State.Items.Clear();
        ddl_City.Enabled = true;
        ddl_State.Enabled = true;
        if (System.Text.RegularExpressions.Regex.IsMatch(strZip.ToUpper(), @"(^\d{5}$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} +\d{1}[A-Z]{1}\d{1}$)"))
        {
            try
            {
                com.codebump.GeoPlaces g = new com.codebump.GeoPlaces();

                com.codebump.AuthenticationHeader authHeader = new com.codebump.AuthenticationHeader();
                authHeader.SessionID = "6JV2ZA4lgG1YRR+HG+JU27QWk9zI3rpRWY2iG2mzNPcdieEQXfQv0OUY0EZ+pOTxhwI1NCuF7b2oY+U/bozy0mhjFHmpaXvb";
                g.AuthenticationHeaderValue = authHeader;

                com.codebump.GeoPlaceDistance[] places = g.GetPlacesInside(strZip, "");

                for (int i = 0; i < places.Length; i++)
                {
                    com.codebump.GeoPlaceDistance place = places[i];
                    ListItem li = new ListItem(place.ToPlace, place.ToState + "," + place.ToPlace);
                    ddl_City.Items.Add(li);
                }

                ddl_State.Items.Add(ddl_City.SelectedItem.Value.Split(",".ToCharArray())[0]);

                //ddlCity.SelectedIndex = 0;

                if (System.Text.RegularExpressions.Regex.IsMatch(strZip.ToUpper(), @"(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)"))
                {
                    ddl_Country.SelectedValue = "CANADA";
                }
                else
                {
                    ddl_Country.SelectedValue = "USA";
                }

                if (ddl_City.Items.Count <= 0)
                {
                    ddl_City.Items.Add("No Cities Found");
                    ddl_State.Items.Add("No States Found");
                    ddl_City.Enabled = false;
                    ddl_State.Enabled = false;
                }
                else
                {
                    ddl_City.Items.Insert(0, "Select a City");
                    ddl_City.SelectedIndex = 0;
                    ddl_State.Enabled = false;
                }
            }
            catch
            {
                ddl_City.Items.Add("No Cities Found");
                ddl_State.Items.Add("No States Found");
                ddl_City.Enabled = false;
                ddl_State.Enabled = false;
            }
        }
        else
        {
            ddl_City.Items.Add("Invalid Zip");
            ddl_City.Enabled = false;
            ddl_State.Items.Add("Invalid Zip");
            ddl_State.Enabled = false;

        }
    }

    public DataAccess.CardType GetCardType(string cardType)
    {
        switch (cardType)
        {
            case "A":
                return DataAccess.CardType.AmericanExpress;
            case "V":
                return DataAccess.CardType.Visa;
            case "D":
                return DataAccess.CardType.Discover;
            case "M":
                return DataAccess.CardType.MasterCard;
            default:
                return DataAccess.CardType.Visa;
        }
    }


    protected void btnFAQ_Click(object sender, EventArgs e)
    {
        pnlFAQ.Visible = !pnlFAQ.Visible;
        pnlWizard.Visible = !pnlWizard.Visible;
    }

    protected void btnCostQuestions_Click(object sender, EventArgs e)
    {
        pnlCost.Visible = !pnlCost.Visible;
    }

    public void PreAuth()
    {

        //step 1 - create the request
        var request = new AuthorizationRequest(tbCCNumber.ToString(), tbExpDate.ToString(), Convert.ToDecimal(lblAmount.Text),
            "Test Transaction");

        //step 2 - create the gateway, sending in your credentials
        var gate = new Gateway("8H7VgC2aa58", "829V6pP7h5M8GraP");

        //step 3 - make some money
        var response = gate.Send(request);

        //Console.WriteLine("{0}: {1}", response.ResponseCode, response.Message);
        //Console.Read();
        lblPreAuthResult.Text = response.ResponseCode + ", " + response.Message;
    }


    public bool PreAuth2()
    {

        bool ccCheck = false;

        //check to make sure that we have card info to send to the pre-auth
        ccCheck = !(string.IsNullOrEmpty(ddlCardType.SelectedItem.Text) ||
            string.IsNullOrEmpty(tbCCNumber.Text) ||
            string.IsNullOrEmpty(tbCCV.Text) ||
            string.IsNullOrEmpty(tbExpDate.Text) || //&&
            (tbExpDate.Text.Length < 4) ||          //this has to be before the convert.toint32 statement on it so it fails before attempting that. Otherwise it throws a yellow screen.
            Convert.ToInt32(tbExpDate.Text.Substring(0, 2)) > 12) &&
            (((DataAccess)Session["App"]).IsValidCC(GetCardType(ddlCardType.SelectedValue), tbCCNumber.Text)) &&
            (System.Text.RegularExpressions.Regex.IsMatch(tbCCV.Text, @"^[\d]+$")) &&
            (System.Text.RegularExpressions.Regex.IsMatch(tbExpDate.Text, @"^[\d]+$"));

        if (ccCheck)
        {
            lblPreAuthResult.Text = "";
            String post_url = "https://secure.authorize.net/gateway/transact.dll";
            //String post_url = "https://apitest.authorize.net/xml/v1/request.api";
            Dictionary<string, string> post_values = new Dictionary<string, string>();
            //the API Login ID and Transaction Key must be replaced with valid values
            post_values.Add("x_login", "8H7VgC2aa58");
            post_values.Add("x_tran_key", "829V6pP7h5M8GraP");
            post_values.Add("x_delim_data", "TRUE");
            post_values.Add("x_delim_char", "|");
            post_values.Add("x_relay_response", "FALSE");
            post_values.Add("x_version", "3.1");

            //post_values.Add("x_type", "AUTH_CAPTURE");
            post_values.Add("x_type", "AUTH_ONLY");
            post_values.Add("x_method", "CC");
            post_values.Add("x_card_num", tbCCNumber.Text);
            //post_values.Add("x_card_num", "4111111111111111");
            post_values.Add("x_exp_date", tbExpDate.Text);
            //post_values.Add("x_exp_date", "1111");

            post_values.Add("x_amount", lblAmount.Text);
            //post_values.Add("x_description", "Sample Transaction");
            post_values.Add("x_test_request", "FALSE");          ////////********************* CHANGE TO FALSE FOR PRODUCTION!!! *********************

            //post_values.Add("x_first_name", "John");
            //post_values.Add("x_last_name", "Doe");
            //post_values.Add("x_address", "1234 Street");
            //post_values.Add("x_state", "WA");
            //post_values.Add("x_zip", "98004");
            // Additional fields can be added here as outlined in the AIM integration
            // guide at: http://developer.authorize.net

            // This section takes the input fields and converts them to the proper format
            // for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"
            String post_string = "";

            foreach (KeyValuePair<string, string> post_value in post_values)
            {
                post_string += post_value.Key + "=" + HttpUtility.UrlEncode(post_value.Value) + "&";
            }
            post_string = post_string.TrimEnd('&');

            // create an HttpWebRequest object to communicate with Authorize.net
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(post_url);
            objRequest.Method = "POST";
            objRequest.ContentLength = post_string.Length;
            objRequest.ContentType = "application/x-www-form-urlencoded";

            // post data is sent as a stream
            StreamWriter myWriter = null;
            myWriter = new StreamWriter(objRequest.GetRequestStream());
            myWriter.Write(post_string);
            myWriter.Close();

            // returned values are returned as a stream, then read into a string
            String post_response;
            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
            {
                post_response = responseStream.ReadToEnd();
                responseStream.Close();
            }

            // the response string is broken into an array
            // The split character specified here must match the delimiting character specified above
            Array response_array = post_response.Split('|');
            //string[] response_array = post_response.Split('|');
            //       lblPreAuthResult.Text = "response code: " + response_array.GetValue(0) + ", response reason: " + response_array.GetValue(1) ;

            // the results are output to the screen in the form of an html numbered list.
            //resultSpan.InnerHtml += "<OL> \n";
            foreach (string value in response_array)
            {
                //resultSpan.InnerHtml += "<LI>" + value + "&nbsp;</LI> \n";
                lblPreAuthResult.Text += ": " + value;
            }
            //resultSpan.InnerHtml += "</OL> \n";
            lblPreAuthResult.Text = "response code: " + response_array.GetValue(0).ToString() + ", response sub code: " + response_array.GetValue(1).ToString() + ", response reason code: " + response_array.GetValue(2).ToString() + ", response reason: " + response_array.GetValue(3).ToString() + ", authorization code: " + response_array.GetValue(4).ToString();
            ((DataAccess)Session["App"]).PutCallData("Webresponse", lblPreAuthResult.Text);
            //lblPreauthCode.Text = "";
            //lblAuthTransID.Text = "";
            lblAuthTransID.Text = response_array.GetValue(6).ToString();
            ((DataAccess)Session["App"]).PutCallData("TransactionID", lblAuthTransID.Text);
            lblPreauthCode.Text = response_array.GetValue(4).ToString();
            ((DataAccess)Session["App"]).PutCallData("AuthCode", lblPreauthCode.Text);
            ((DataAccess)Session["App"]).CommitCallData();
        }
        return ccCheck;        
    }
 
    protected void ddlOrderClose_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlOrderClose.SelectedItem.Text == "Order Close - Yes")
        {
            pnlOrderClose.Visible = true;
        }
        else
        {
            pnlOrderClose.Visible = false;
        }
        if (ddlOrderClose.SelectedItem.Text == "Order Close - No")
        {
            pnlOrderNo.Visible = true;
        }
        else
        {
            pnlOrderNo.Visible = false;
        }

    }

    protected void cbDownsell_CheckedChanged(object sender, EventArgs e)
    {
        if (cbDownsell.Checked)
        {
            ddlOnePay.SelectedIndex = 0;
        }
    }
    protected void ddlOnePay_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlOnePay.SelectedItem.Text == "No")
        {
            pnlOnePay.Visible = true;
        }
    }
    protected void tbFirstName_TextChanged(object sender, EventArgs e)
    {
        sCust = tbFirstName.Text;
        lblName1.Text = tbFirstName.Text;
        lblName2.Text = tbFirstName.Text;
        lblName3.Text = tbFirstName.Text;
        lblName4.Text = tbFirstName.Text;
        lblName5.Text = tbFirstName.Text;
        lblName6.Text = tbFirstName.Text;
        lblName7.Text = tbFirstName.Text;
        lblName8.Text = tbFirstName.Text;
        lblName9.Text = tbFirstName.Text;
        lblName10.Text = tbFirstName.Text;
        lblName11.Text = tbFirstName.Text;
        lblName12.Text = tbFirstName.Text;
        lblName13.Text = tbFirstName.Text;
        lblName14.Text = tbFirstName.Text;
        lblName15.Text = tbFirstName.Text;
        lblName16.Text = tbFirstName.Text;
        lblName17.Text = tbFirstName.Text;
        lblName18.Text = tbFirstName.Text;
        lblName19.Text = tbFirstName.Text;
        //lblName20.Text = tbFirstName.Text;
        //lblName21.Text = tbFirstName.Text;

        tbLastName.Focus();
    }

 
    protected void cbEmployee_CheckedChanged(object sender, EventArgs e)
    {
        if (cbEmployee.Checked)
        {
            ddlOnePay.SelectedItem.Text = "No";
            ddlOnePay.Enabled = false;
        }
        else
        {
            ddlOnePay.SelectedItem.Text = "Choose One";
            ddlOnePay.Enabled = true;
           
        }
        
    }

    protected void btnPreAuth_Click(object sender, EventArgs e)
    {
        if (PreAuth2())
        {
            btnPreAuth.Enabled = false;
        }
    }


    



    // The UDI Auth token identifies the submitting system, and the account that it is submitting to. 
    //  These tokens are issued by OMX account administrators, usually filtered to specific IP addresses and APIs to be permitted.

    private const string TOKEN = "jAzQefQVssOgrcDfMijvhPJnNQkApgGerMLtbVZQSTMzCjHcXXnWxqZuQldoUqFlLJOEqjdQisCodjLEiiDsTKHaNrDQSKVCnAOSudMNTwNeOLrGAygMMmsacNRZFnXyxZaCvSjfvPzwXDmcaWpuDjPaiOQHlNiFzpHPKOlIpbqXNVdyBPYJXDUnjauGbCTIHTXHWxslLHeCSSnmKsfwOyHWvtFJuEGNhHqTYvCexNYqzrurNhVJwxUimalCRIQ";
         //public string TOKEN = "jAzQefQVssOgrcDfMijvhPJnNQkApgGerMLtbVZQSTMzCjHcXXnWxqZuQldoUqFlLJOEqjdQisCodjLEiiDsTKHaNrDQSKVCnAOSudMNTwNeOLrGAygMMmsacNRZFnXyxZaCvSjfvPzwXDmcaWpuDjPaiOQHlNiFzpHPKOlIpbqXNVdyBPYJXDUnjauGbCTIHTXHWxslLHeCSSnmKsfwOyHWvtFJuEGNhHqTYvCexNYqzrurNhVJwxUimalCRIQ";



    public string SubmitUDOAOrder()  //originally was public string
    {
        int errNum = 0;
        string errDesc = "";
        string result = "";

        XmlDocument xmlRequest = new XmlDocument();
        XmlDeclaration declaration = xmlRequest.CreateXmlDeclaration("1.0", "UTF-8", null);
        xmlRequest.AppendChild(declaration);

        XmlElement root = xmlRequest.CreateElement("UDOARequest");
        root.SetAttribute("version", "2.00");

        XmlElement udiparam = CreateElement(xmlRequest, "UDIParameter", null, null, null);
        udiparam.AppendChild(CreateElement(xmlRequest, "Parameter", "UniversalDirectOrderAppending", "key", "RequestType"));
       //
        //UDI Auth Token - this identifies the system sending the request, and the account that the request is for.
        udiparam.AppendChild(CreateElement(xmlRequest, "Parameter", TOKEN, "key", "HTTPBizID"));

        //QueueFlag determines whether OMX will Queue any problem orders for manual resolution within the OMX interface, 
        // or return the errors to the requesting system and not accept the order.
        udiparam.AppendChild(CreateElement(xmlRequest, "Parameter", "True", "key", "QueueFlag"));

        //Keycode - this is also known as the Offer Code
        if (cbEmployee.Checked)
        {
            udiparam.AppendChild(CreateElement(xmlRequest, "Parameter", "EMPSTORE", "key", "Keycode"));
        }
        else
        {
            udiparam.AppendChild(CreateElement(xmlRequest, "Parameter", "FS-INSERTFR", "key", "Keycode"));
        }
        udiparam.AppendChild(CreateElement(xmlRequest, "Parameter", "False", "key", "VerifyFlag"));

        root.AppendChild(udiparam);

        XmlElement header = CreateElement(xmlRequest, "Header", null, null, null);

        //The StoreCode tells OMX what submitting system the Order ID relates to, so that it can check for duplicate
        // submissions (a single order ID, received several times, with the same store code).
        header.AppendChild(CreateElement(xmlRequest, "StoreCode", "Focus", null, null));

        //The OrderID is the submitting system's order identifier/reference - this is used to easily locate orders in OMX 
        // given the front-end order identifier (eg for customer service calls immediately after the web order is placed),
        // and also to detect duplicate submissions of the same order - for the same OrderID and the same StoreCode.
        header.AppendChild(CreateElement(xmlRequest, "OrderID", Session["listid"].ToString(), null, null));

        //The date of the customer's order - this may differ substantially from teh submission date, in case of queued submissions.
        //header.AppendChild(CreateElement(xmlRequest, "OrderDate", Session["callstart"].ToString(), null, null));
        header.AppendChild(CreateElement(xmlRequest, "OrderDate", string.Format("{0:yyyy-MM-dd}", System.DateTime.Today), null, null));

        //The order channel (internet, phone, etc)
        header.AppendChild(CreateElement(xmlRequest, "OriginType", "3", null, null));

        root.AppendChild(header);

        XmlElement customer = CreateElement(xmlRequest, "Customer", null, null, null);
        XmlElement address = CreateElement(xmlRequest, "Address", null, "type", "BillTo");
        address.AppendChild(CreateElement(xmlRequest, "TitleCode", "0", null, null));
        address.AppendChild(CreateElement(xmlRequest, "Firstname", tbFirstName.Text, null, null));
        address.AppendChild(CreateElement(xmlRequest, "MidInitial", null, null, null));
        address.AppendChild(CreateElement(xmlRequest, "Lastname", tbLastName.Text, null, null));
        address.AppendChild(CreateElement(xmlRequest, "Address1", tbAddr.Text, null, null));
        address.AppendChild(CreateElement(xmlRequest, "Address2", tbAddr2.Text, null, null));
        address.AppendChild(CreateElement(xmlRequest, "City", tbCity.Text, null, null));
        address.AppendChild(CreateElement(xmlRequest, "State", tbState.Text, null, null));
        address.AppendChild(CreateElement(xmlRequest, "ZIP", tbZip.Text, null, null));
        if (ddlCountry.SelectedItem.Text == "USA")
        {
            address.AppendChild(CreateElement(xmlRequest, "TLD", "US", null, null));
        }
        if (ddlCountry.SelectedItem.Text == "CANADA")
        {
            address.AppendChild(CreateElement(xmlRequest, "TLD", "CA", null, null));
        }
        address.AppendChild(CreateElement(xmlRequest, "PhoneNumber", tbPhone.Text, null, null));
        customer.AppendChild(address);
        root.AppendChild(customer);

        XmlElement shippingInfo = CreateElement(xmlRequest, "ShippingInformation", null, null, null);
        XmlElement shipaddress = CreateElement(xmlRequest, "Address", null, "type", "ShipTo");
        shipaddress.AppendChild(CreateElement(xmlRequest, "TitleCode", "0", null, null));
        shipaddress.AppendChild(CreateElement(xmlRequest, "Firstname", tbFirstName.Text, null, null));
        shipaddress.AppendChild(CreateElement(xmlRequest, "Lastname", tbLastName.Text, null, null));
        if (cbShipping.Checked)
        {
            shipaddress.AppendChild(CreateElement(xmlRequest, "Address1", tbShipAddr.Text, null, null));
            shipaddress.AppendChild(CreateElement(xmlRequest, "Address2", tbShipaddr2.Text, null, null));
            shipaddress.AppendChild(CreateElement(xmlRequest, "City", ddlShipCity.SelectedItem.Text, null, null));
            shipaddress.AppendChild(CreateElement(xmlRequest, "State", ddlShipState.SelectedItem.Text, null, null));
            shipaddress.AppendChild(CreateElement(xmlRequest, "ZIP", tbShipZip.Text, null, null));
            //shipaddress.AppendChild(CreateElement(xmlRequest, "TLD", ddlShipCountry.SelectedItem.Text, null, null));
            if (ddlShipCountry.SelectedItem.Text == "USA")
            {
                shipaddress.AppendChild(CreateElement(xmlRequest, "TLD", "US", null, null));
            }
            if (ddlShipCountry.SelectedItem.Text == "CANADA")
            {
                shipaddress.AppendChild(CreateElement(xmlRequest, "TLD", "CA", null, null));
            }
        }
        else
        {
            shipaddress.AppendChild(CreateElement(xmlRequest, "Address1", tbAddr.Text, null, null));
            shipaddress.AppendChild(CreateElement(xmlRequest, "Address2", tbAddr2.Text, null, null));
            shipaddress.AppendChild(CreateElement(xmlRequest, "City", tbCity.Text, null, null));
            shipaddress.AppendChild(CreateElement(xmlRequest, "State", tbState.Text, null, null));
            shipaddress.AppendChild(CreateElement(xmlRequest, "ZIP", tbZip.Text, null, null));
            //shipaddress.AppendChild(CreateElement(xmlRequest, "TLD", ddlCountry.SelectedItem.Text, null, null));
            if (ddlCountry.SelectedItem.Text == "USA")
            {
                shipaddress.AppendChild(CreateElement(xmlRequest, "TLD", "US", null, null));
            }
            if (ddlCountry.SelectedItem.Text == "CANADA")
            {
                shipaddress.AppendChild(CreateElement(xmlRequest, "TLD", "CA", null, null));
            }
        }
        shippingInfo.AppendChild(shipaddress);
        if (ddlPriorityShip.SelectedItem.Text == "Yes")
        {
            XmlElement methodCode = CreateElement(xmlRequest, "MethodCode", "2", null, null);
            shippingInfo.AppendChild(methodCode);
        }
        else
        {
            XmlElement methodCode = CreateElement(xmlRequest, "MethodCode", "1", null, null);
            shippingInfo.AppendChild(methodCode);
        }
        
        XmlElement shippingAmount = CreateElement(xmlRequest, "ShippingAmount", lblShip.Text, null, null);
        shippingInfo.AppendChild(shippingAmount);
        root.AppendChild(shippingInfo);

        XmlElement paymentType = CreateElement(xmlRequest, "Payment", null, "type", "1");
        paymentType.AppendChild(CreateElement(xmlRequest, "CardNumber", tbCCNumber.Text, null, null));
        paymentType.AppendChild(CreateElement(xmlRequest, "CardVerification", null, null, null));
        paymentType.AppendChild(CreateElement(xmlRequest, "CardExpDateMonth", tbExpDate.Text.Substring(0, 2), null, null));
        paymentType.AppendChild(CreateElement(xmlRequest, "CardExpDateYear", "20" + tbExpDate.Text.Substring(2, 2), null, null));
        paymentType.AppendChild(CreateElement(xmlRequest, "RealTimeCreditCardProcessing", "False", null, null));
        paymentType.AppendChild(CreateElement(xmlRequest, "CardStatus", "11", null, null));
        paymentType.AppendChild(CreateElement(xmlRequest, "CardAuthCode", lblPreauthCode.Text, null, null));
        paymentType.AppendChild(CreateElement(xmlRequest, "CardTransactionID", lblAuthTransID.Text, null, null));
        //paymentType.AppendChild(CreateElement(xmlRequest, "CardAuthorizationAmount", total.ToString(), null, null)); //this kept inserting 0, though total is no initialized after ConfirmOrder pre-logic.
        paymentType.AppendChild(CreateElement(xmlRequest, "CardAuthorizationAmount", lblAmount.Text, null, null));
        paymentType.AppendChild(CreateElement(xmlRequest, "BankAccountNumber", null, null, null));
        paymentType.AppendChild(CreateElement(xmlRequest, "BankRoutingNumber", null, null, null));
        root.AppendChild(paymentType);

        XmlElement orderDetail = CreateElement(xmlRequest, "OrderDetail", null, null, null);

        
        int itemnumber = 1;
        foreach (DataRow r in ((DataAccess)Session["App"]).GetOrder().Rows)
        {
            if (r["ProductTypeID"].ToString() == "1")
            {
                continue;
            }
                XmlElement lineItem = CreateElement(xmlRequest, "LineItem", null, "lineNumber", itemnumber.ToString());
                if (r["ProductTypeID"].ToString() == "3")
                {
                    //if (r["ProductID"].ToString() == "374" || r["ProductID"].ToString() == "375")
                    //{
                    //    lineItem.AppendChild(CreateElement(xmlRequest, "PaymentPlanID", "0", null, null));
                    //    continue;
                    //}
                    if (ddlOnePay.SelectedItem.Text == "Yes" || cbEmployee.Checked)
                    {
                        lineItem.AppendChild(CreateElement(xmlRequest, "PaymentPlanID", "0", null, null));
                    }
                    else
                    {
                        if (cbDownsell.Checked)
                        {
                            lineItem.AppendChild(CreateElement(xmlRequest, "PaymentPlanID", "16", null, null));
                        }
                        else
                        {
                            lineItem.AppendChild(CreateElement(xmlRequest, "PaymentPlanID", "15", null, null));
                        }
                    }
                }
                else if (r["ProductID"].ToString() == "334" || r["ProductID"].ToString() == "335" || r["ProductID"].ToString() == "426")
                {
                    if (ddlOnePay.SelectedItem.Text == "Yes")
                    {
                        lineItem.AppendChild(CreateElement(xmlRequest, "PaymentPlanID", "0", null, null));
                    }
                    else
                    {
                        lineItem.AppendChild(CreateElement(xmlRequest, "PaymentPlanID", "15", null, null));
                    }
                }
                else
                {
                    lineItem.AppendChild(CreateElement(xmlRequest, "PaymentPlanID", "0", null, null));
                }
            
                //lineItem.AppendChild(CreateElement(xmlRequest, "ItemCode", r["ProductID"].ToString(), null, null));
                lineItem.AppendChild(CreateElement(xmlRequest, "ItemCode", (((DataAccess)Session["App"]).GetProducts("ProductID", r["ProductID"].ToString())).Rows[0]["Group1"].ToString(), null, null));
                //lineItem.AppendChild(CreateElement(xmlRequest, "Quantity", r["Quantity"].ToString(), null, null));
                lineItem.AppendChild(CreateElement(xmlRequest, "Quantity", r["Quantity"].ToString(), null, null));
                //if (ddlOnePay.SelectedItem.Text == "No" && (r["ProductID"].ToString()=="343" || r["ProductID"].ToString()=="344" || r["ProductID"].ToString()=="345"))
                //{
                //    lineItem.AppendChild(CreateElement(xmlRequest, "UnitPrice", "284.80", null, null));
                //}
                //else
                //{
                    lineItem.AppendChild(CreateElement(xmlRequest, "UnitPrice", r["BaseRevenue"].ToString(), null, null));
                //}
                orderDetail.AppendChild(lineItem);
                root.AppendChild(orderDetail);
            itemnumber++;
        }

        XmlElement customfields = CreateElement(xmlRequest, "CustomFields", null, null, null);
        XmlElement report = CreateElement(xmlRequest, "Report", null, null, null);
        report.AppendChild(CreateElement(xmlRequest, "Field", string.Format("{0:yyyy-MM-dd}", System.DateTime.Today), "fieldName", "OriginalOrderDate"));
//        report.AppendChild(CreateElement(xmlRequest, "Field", "2", "fieldName", "PaymentPlanID"));
        report.AppendChild(CreateElement(xmlRequest, "Field", Session["agentid"].ToString(), "fieldName", "AgentID"));
//        report.AppendChild(CreateElement(xmlRequest, "Field", "RadiancyFR.aspx", "fieldName", "ScriptID"));
        switch (Session["dnis"].ToString())
        {
            case "8662127784":
                report.AppendChild(CreateElement(xmlRequest, "Field", "RFRENCHFSTV-104.90", "fieldName", "ScriptID"));
                break;
            case "8662127770":
                report.AppendChild(CreateElement(xmlRequest, "Field", "RFRENCHFSTV-104.90", "fieldName", "ScriptID"));
                break;
            case "8662127754":
                report.AppendChild(CreateElement(xmlRequest, "Field", "RFRENCHINS-104.90", "fieldName", "ScriptID"));
                break;
            case "8662127783":
                report.AppendChild(CreateElement(xmlRequest, "Field", "RESPANOLFSTV-104.90", "fieldName", "ScriptID"));
                break;
        }
        report.AppendChild(CreateElement(xmlRequest, "Field", "NONO", "fieldName", "OfferCode"));
        report.AppendChild(CreateElement(xmlRequest, "Field", "Intelemedia", "fieldName", "Agency"));
        report.AppendChild(CreateElement(xmlRequest, "Field", Session["ani"].ToString(), "fieldName", "IntelemediaID"));
        report.AppendChild(CreateElement(xmlRequest, "Field","", "fieldName", "CustomerANI"));
        report.AppendChild(CreateElement(xmlRequest, "Field", Session["dnis"].ToString(), "fieldname", "800#"));
        customfields.AppendChild(report);
        root.AppendChild(customfields);


        xmlRequest.AppendChild(root);
        //xmlRequest.Save(@"C:\Users\Aaron.Christensen.FOCUSSERVICES\Documents\FRtest.xml");                                                    //.............comment out for production!~!
//        ((DataAccess)Session["App"]).PutCallData("AuthCode", xmlRequest.Text);        

        //Moved to put xmlresponse in db so we have it for all orders that are built.
        ((DataAccess)Session["App"]).PutCallData("XMLResponse", ((DataAccess)Session["App"]).EnryptData(xmlRequest.InnerXml));
        ((DataAccess)Session["App"]).CommitCallData();

        // Send the Request to OMX
        string response = PostRequest("https://api.omx.ordermotion.com/hdde/xml/udi.asp", xmlRequest.OuterXml, ref errNum, ref errDesc);

        // Handle the HTTP errors
        if (errNum != 0)
        {
            if (errNum == 500)
            {
                // Handle critical OMX errors
                if (!String.IsNullOrEmpty(response))
                {
                    string errors = "";
                    XmlDocument xmlResponse = new XmlDocument();
                    xmlResponse.LoadXml(response);
                    foreach (XmlNode error in xmlResponse.SelectNodes("//ErrorData/Error"))
                        errors += error.InnerText + " - ";
                    foreach (XmlNode error in xmlResponse.SelectNodes("//Result/Reference"))
                        errors += "PX error reference: " + error.InnerText + " - ";
                    throw new Exception(errors);
                    
                }
            }
            throw new Exception("ERROR " + errNum + ": " + errDesc);
        }

        // Handle the response content
        if (!String.IsNullOrEmpty(response))
        {
            XmlDocument xmlResponse = new XmlDocument();
            xmlResponse.LoadXml(response);

            // Handle the OMX errors
            if (xmlResponse.SelectNodes("//Success").Count > 0 && xmlResponse.SelectSingleNode("//Success").InnerText == "0")
            {
                string errors = "";
                foreach (XmlNode error in xmlResponse.SelectNodes("//UDOAResponse/ErrorData/Error"))
                    errors += error.InnerText + " - ";
                throw new Exception(errors);
            }

            // XML processing
            if (xmlResponse.SelectNodes("//UDOARequest/Header/OrderNumber").Count > 0)
            {
                result = "The order has been created. Assigned order number: " + xmlResponse.SelectSingleNode("//UDOARequest/Header/OrderNumber").InnerText;
                //result = xmlResponse.OuterXml;
            }
            else
            {
                result = "The order has been queued.";
            }
        }

        return result;
        //return true;
    }

    private XmlElement CreateElement(XmlDocument doc, string name, string value, string attrName, string attrValue)
    {
        XmlElement element = doc.CreateElement(name);
        if (!String.IsNullOrEmpty(value))
        {
            element.InnerText = System.Security.SecurityElement.Escape(value);
        }
        if (!String.IsNullOrEmpty(attrName))
        {
            element.SetAttribute(attrName, System.Security.SecurityElement.Escape(attrValue));
        }
        return element;
    }

    private string PostRequest(string url, string data, ref int errorNumber, ref string errorMessage)
    {
        // Create the Web Request Object 
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        request.Timeout = 60000;
        request.ContentType = "text/xml; charset=utf-8";

        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
        request.ContentLength = bytes.Length;

        Stream outputStream = request.GetRequestStream();
        outputStream.Write(bytes, 0, bytes.Length);
        outputStream.Close();

        WebResponse response = null;
        try
        {
            response = request.GetResponse();
            errorNumber = 0;
        }
        catch (System.Net.WebException e)
        {
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                errorNumber = (int)((HttpWebResponse)e.Response).StatusCode;
                errorMessage = ((HttpWebResponse)e.Response).StatusDescription;
                //get the response anyway
                response = e.Response;
            }
            else
            {
                errorNumber = 2;
                errorMessage = e.Message;
            }
        }
        catch (Exception e)
        {
            errorNumber = 1;
            errorMessage = e.Message;
        }

        if (response != null)
        {
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            return reader.ReadToEnd();
        }
        else
        {
            return "";
        }
    }
    protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cbEmployee.Checked && ddlColor.SelectedItem.Text == "Black")
        {
            ddlColor.SelectedIndex = 0;
        }
    }
    protected void ddlAddUnit_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlAddUnit.SelectedIndex > 0 && ddlAddUnit.SelectedIndex < 4)
        {
            ddlAddUnitQty.Visible = true;
        }
        else
        {
            ddlAddUnitQty.Visible = false;
            ddlAddUnitQty.SelectedIndex = 0;
        }

        ddlAddUnitQty_SelectedIndexChanged(null, null);
    }
    protected void ddlFaceBundle_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlFaceBundle.SelectedIndex == 1)
        {
            ddlFaceBundleQty.Visible = true;
        }
        else
        {
            ddlFaceBundleQty.Visible = false;
            ddlFaceBundleQty.SelectedIndex = 0;
        }
    }
    protected void ddlBodyBundle_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlBodyBundle.SelectedIndex == 1)
        {
            ddlBodyBundleQty.Visible = true;
        }
        else
        {
            ddlBodyBundleQty.Visible = false;
            ddlBodyBundleQty.SelectedIndex = 0;
        }
    }
    protected void ddlSmooth_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlSmooth.SelectedIndex == 1)
        {
            ddlSmoothQty.Visible = true;
        }
        else
        {
            ddlSmoothQty.Visible = false;
            ddlSmoothQty.SelectedIndex = 0;
        }
    }
    protected void ddlSkin_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlSkin.SelectedIndex == 1)
        {
            ddlSkinQty.Visible = true;
        }
        else
        {
            ddlSkinQty.Visible = false;
            ddlSkinQty.SelectedIndex = 0;
        }
    }
    protected void ddlAddUnitQty_SelectedIndexChanged(object sender, EventArgs e)
    {

        for (int i = 1; i <= 4; i++)
        {
            ddlFaceBundleQty.Items[i].Enabled = false;
            ddlBodyBundleQty.Items[i].Enabled = false;
            ddlSmoothQty.Items[i].Enabled = false;
            ddlSkinQty.Items[i].Enabled = false;
        }

        if (ddlAddUnit.SelectedIndex > 0 && ddlAddUnit.SelectedIndex < 4)
        {
            for (int i = 1; i <= ddlAddUnitQty.SelectedIndex + 1; i++)
            {
                ddlFaceBundleQty.Items[i].Enabled = true;
                ddlBodyBundleQty.Items[i].Enabled = true;
                ddlSmoothQty.Items[i].Enabled = true;
                ddlSkinQty.Items[i].Enabled = true;
            }
        }
    }
    protected void ddlPriorityShip_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void buildOrder2()
    {
        ((DataAccess)Session["App"]).GetOrder().Rows.Clear();
        total = 0;
        prods = "";
        additionalPay = 0;
        shipping = 0;
        prods = ddlColor.SelectedItem.Text + " NoNo!";
        pnl1PayConf.Visible = false;
        pnl3PayConf.Visible = false;
        pnlTrialConf.Visible = false;

        if (!cbEmployee.Checked)
        {
            addMain(424, 425, 423, false);  //add main product for non-employee
            addAddtl(); //add additional units

            ///One-pay
            if (ddlOnePay.SelectedItem.Text == "Yes")
            {
                makevis(pnl1PayConf, "ONEPFR");
                addOtherProds(false);
                addShipping(true);

                ((DataAccess)Session["App"]).PutOrderItem(341, 1); //add free warranty

                total += 3 * additionalPay;  //additional payment values are total/3. For one pay, we would undo that /3. 
            }
            ///deferred payment
            else if (ddlOnePay.SelectedValue == "0" && cbDownsell.Checked)
            {

                //additional payment values are total/3. For deferred payments, the total will be shipping plus one-pay + 1 pmt for 3-pay + 0 for main.
                //the total for recurring will be 3-pay + main's 3-pay

                additionalPay = 0; //this line gets rid of the initial payment for just the main product product as that is the only one that's deferred. 
                
                makevis(pnlTrialConf, "TRILFR");
                addOtherProds(false);
                addShipping(false);

                if (ddl2yrWarranty.SelectedValue == "19.95")  //No to one pay. yes to warranty
                {
                    total = total + 19.95;
                    prods = prods + ", plus the upgrade 2-year warranty";
                    ((DataAccess)Session["App"]).PutOrderItem(342, 1);              //add warranty with cost
                }
                total += additionalPay;  //additional payment values are total/3. For deferred payments, the total will be shipping plus one-pay items + 3-pay (not including main).
                additionalPay += 89.95; //re-add payment amount for main prod so it's in the recurring payment total.
            }
            ///3-pay
            else
            {
                makevis(pnl3PayConf, "BAS1FR");
                addOtherProds(false);
                addShipping(false);

                if (ddl2yrWarranty.SelectedValue == "19.95")  //No to one pay. yes to warranty
                {
                    total = total + 19.95;
                    prods = prods + ", plus the upgrade 2-year warranty";
                    ((DataAccess)Session["App"]).PutOrderItem(342, 1);              //add warranty with cost
                }

                total += additionalPay; //additional payment values are total/3. for 3-pay, we leave this as is.
            }
            addTax();
            total += shipping;
        }
        else
        {

            makevis(pnl1PayConf, "ONEPFR");

            addMain(424, 425, 0, true); //add main product for employee

            addAddtl();
            addOtherProds(true);
            total += 3 * additionalPay;  //additional payment values are total/3. For one pay, we would undo that /3. 
            addTax();
        }

        lblTrialProds.Text = prods;
        lblAddPay.Text = additionalPay.ToString();
        lblTrialTotal.Text = total.ToString();


        lbl1PayProds.Text = prods;
        lbl1PayTotal.Text = total.ToString();


        lbl3PayProds.Text = prods;
        lbl3PayTotal.Text = total.ToString();
        lblAdditionalPay.Text = additionalPay.ToString();

        lblShip.Text = shipping.ToString();
        lblAmount.Text = total.ToString();

    }
    protected void addMain(int pinkID, int silverID, int blackID, bool Employee)
    {
        //the index variables are the product id's for the corresponding product
        switch (ddlColor.SelectedIndex)
        {
            case 1:
                ((DataAccess)Session["App"]).PutOrderItem(pinkID, 1);
                break;
            case 2:
                ((DataAccess)Session["App"]).PutOrderItem(silverID, 1);
                break;
            case 3:
                ((DataAccess)Session["App"]).PutOrderItem(blackID, 1);
                break;
            default:
                if (Employee)
                {
                    ((DataAccess)Session["App"]).PutOrderItem(pinkID, 1);
                }
                else
                {
                    ((DataAccess)Session["App"]).PutOrderItem(silverID, 1);
                }
                break;
        }
        if (Employee)
        {
            total += 50;
        }
        else
        {
            additionalPay += 89.95;
        }
    }
    protected void addAddtl()
    {
        switch (ddlAddUnit.SelectedIndex)
        {
            case 0:
                break;
            case 1:
                ((DataAccess)Session["App"]).PutOrderItem(429, Int32.Parse(ddlAddUnitQty.SelectedValue));
                break;
            case 2:
                ((DataAccess)Session["App"]).PutOrderItem(430, Int32.Parse(ddlAddUnitQty.SelectedValue));
                break;
            case 3:
                ((DataAccess)Session["App"]).PutOrderItem(428, Int32.Parse(ddlAddUnitQty.SelectedValue));
                break;
            case 4:
                break;
            default:
                ((DataAccess)Session["App"]).PutOrderItem(429, Int32.Parse(ddlAddUnitQty.SelectedValue));
                break;
        }
        switch (ddlAddUnit.SelectedIndex)
        {
            case 1:
            case 2:
            case 3:
                total = total + (199 * Int32.Parse(ddlAddUnitQty.SelectedValue));
                prods = prods + ", plus an additional " + ddlAddUnitQty.SelectedValue + " " + ddlAddUnit.SelectedItem.Text + " NoNo! Hair unit(s)";
                break;
        }
    }
    protected void addOtherProds(bool employee)
    {
        if (ddlFaceBundle.SelectedItem.Text == "Yes")  //if yes to face bundle, no to one-pay, no deferred pmt
        {
            prods = prods + ", plus " + ddlFaceBundleQty.SelectedValue + " NoNo! Face bundle(s)";
            additionalPay = additionalPay + (26.65 * Int32.Parse(ddlFaceBundleQty.SelectedValue));
            ((DataAccess)Session["App"]).PutOrderItem(334, Int32.Parse(ddlFaceBundleQty.SelectedValue));    //add face bundle
        }

        if (ddlBodyBundle.SelectedItem.Text == "Yes")  //yes to body, no to one-pay, no to deferred
        {
            prods = prods + ", plus " + ddlBodyBundleQty.SelectedValue + " NoNo! Body bundle(s)";
            additionalPay = additionalPay + (19.95 * Int32.Parse(ddlBodyBundleQty.SelectedValue));
            ((DataAccess)Session["App"]).PutOrderItem(335, Int32.Parse(ddlBodyBundleQty.SelectedValue));
        }

        if (ddlSmooth.SelectedItem.Text == "Yes")  //yes smooth, no one-pay, no deferred
        {
            prods = prods + ", plus " + ddlSmoothQty.SelectedValue + " NoNo! Smooth All Over bundle(s)";
            if (employee)
            {
                total = total + (20 * Int32.Parse(ddlSmoothQty.SelectedValue));
                ((DataAccess)Session["App"]).PutOrderItem(378, Int32.Parse(ddlSmoothQty.SelectedValue));
            }
            else
            {
                additionalPay = additionalPay + (13.25 * Int32.Parse(ddlSmoothQty.SelectedValue));
                ((DataAccess)Session["App"]).PutOrderItem(426, Int32.Parse(ddlSmoothQty.SelectedValue));
            }
        }
        if (ddlSkin.SelectedItem.Text == "Yes")     //yes skin
        {
            prods = prods + ", plus " + ddlSkinQty.SelectedValue + " NoNo! Skin Acne Treatment System";
            if (employee)
            {
                total = total + (50 * Int32.Parse(ddlSkinQty.SelectedValue));
                ((DataAccess)Session["App"]).PutOrderItem(377, Int32.Parse(ddlSkinQty.SelectedValue));
            }
            else
            {
                total = total + (110 * Int32.Parse(ddlSkinQty.SelectedValue));
                ((DataAccess)Session["App"]).PutOrderItem(430, Int32.Parse(ddlSkinQty.SelectedValue));
            }
        }
        if (cbCharger.Checked && employee)  //unique to employee orders
        {
            total = total + 19.95;
            prods = prods + ", plus an additional charger";
            ((DataAccess)Session["App"]).PutOrderItem(379, 1);
        }
    }
    protected void addShipping(bool onepay)
    {
        if (ddlPriorityShip.SelectedItem.Text == "Yes" && !onepay) //yes rush, no one pay
        {
            shipping = 27.90;
            prods = prods + ", plus priority shipping";
            ((DataAccess)Session["App"]).PutOrderItem(333, 1);
        }
        else if (ddlPriorityShip.SelectedItem.Text == "Yes" && onepay)//yes rush, yes one-pay
        {
            shipping = 12.95;
            prods = prods + ", plus priority shipping";
            ((DataAccess)Session["App"]).PutOrderItem(332, 1);
        }
        else if (ddlPriorityShip.SelectedItem.Text == "No" && onepay)   //no rush, yes one-pay (free shipping)
        {
        }
        else    //no rush, no one-pay
        {
            shipping = 14.95;
            ((DataAccess)Session["App"]).PutOrderItem(331, 1);
        }
    }
    protected void makevis(Panel pnlVis, string pmtType)
    {
        pnlVis.Visible = true;
        ((DataAccess)Session["App"]).PutCallData("webtransfer", pmtType);
    }
    protected void addTax()
    {
        if (cbShipping.Checked)
        {
            if (ddlShipCountry.SelectedValue == "CANADA")
            {
                total *= 1.15;
                additionalPay *= 1.15;
            }
            else
            {
                switch (ddlShipState.SelectedItem.Text)
                {
                    case "NY":
                        total *= 1.08875;
                        additionalPay *= 1.08875;
                        break;
                    case "NJ":
                        total *= 1.07;
                        additionalPay *= 1.07;
                        break;
                    case "GA":
                        total *= 1.08;
                        additionalPay *= 1.08;
                        break;
                }
            }
        }
        else
        {
            if (ddlCountry.SelectedValue == "CANADA")
            {
                total *= 1.15;
                additionalPay *= 1.15;
            }
            else
            {
                switch (ddlState.SelectedItem.Text)
                {
                    case "NY":
                        total *= 1.08875;
                        additionalPay *= 1.08875;
                        break;
                    case "NJ":
                        total *= 1.07;
                        additionalPay *= 1.07;
                        break;
                    case "GA":
                        total *= 1.08;
                        additionalPay *= 1.08;
                        break;
                }
            }
        }

        total = Math.Round(total, 2);
        additionalPay = Math.Round(additionalPay, 2);
    }
    protected void prepopulateFields()
    {
        bool bHasShipInfo = false;
        bHasShipInfo = !(string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShipAddress1")) &&
                        string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShipAddress2")) &&
                        string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShipZip")));

        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("FirstName")))
        {
            tbFirstName.Text = ((DataAccess)Session["App"]).GetCallData("FirstName");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("LastName")))
        {
            tbLastName.Text = ((DataAccess)Session["App"]).GetCallData("LastName");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("Address1")))
        {
            tbAddr.Text = ((DataAccess)Session["App"]).GetCallData("Address1");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("Address2")))
        {
            tbAddr2.Text = ((DataAccess)Session["App"]).GetCallData("Address2");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("Zip")))
        {
            tbZip.Text = ((DataAccess)Session["App"]).GetCallData("Zip");
            btnSearchZip_Click(null, null); //run logic for getting city info from zip
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("PrimaryPhone")))
        {
            tbPhone.Text = ((DataAccess)Session["App"]).GetCallData("PrimaryPhone");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("Email")))
        {
            tbEmail.Text = ((DataAccess)Session["App"]).GetCallData("Email");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShipAddress1")))
        {
            tbShipAddr.Text = ((DataAccess)Session["App"]).GetCallData("ShipAddress1");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShipAddress2")))
        {
            tbShipaddr2.Text = ((DataAccess)Session["App"]).GetCallData("ShipAddress2");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShipZip")))
        {
            tbShipZip.Text = ((DataAccess)Session["App"]).GetCallData("ShipZip");
            btnShipSearchZip_Click(null, null);
        }
        if (bHasShipInfo)
        {
            cbShipping.Checked = true;
            cbShipping_CheckedChanged(null, null);
        }


    }
}